package com.chen.music.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.music.model.*;
import com.chen.music.service.CollectService;
import com.chen.music.service.CommentService;
import com.chen.music.service.ConsumerService;
import com.chen.music.service.RankService;
import com.chen.music.util.CommonResult;
import com.chen.music.util.MessageConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 前端用户 前端控制器
 * </p>
 *
 * @author boat
 * @since 2022-01-13
 */
@RestController
@RequestMapping("/consumer")
@Api(tags = "前台用户管理")
public class ConsumerController {

    @Autowired
    private ConsumerService consumerService;

    @Autowired
    private RankService rankService;

    @Autowired
    private CollectService collectService;

    @Autowired
    private CommentService commentService;

    @PostMapping("/add")
    @ApiOperation("新增用户")
    public CommonResult add(Consumer consumer) {
        try {
            LambdaQueryWrapper<Consumer> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(!StringUtils.isEmpty(consumer.getUsername()), Consumer::getUsername, consumer.getUsername());
            if (consumerService.count(wrapper) > 0) {
                return new CommonResult(200, false, MessageConst.ADMIN_NAME_FAIL);
            } else {
                consumer.setPassword(DigestUtils.md5DigestAsHex(consumer.getPassword().getBytes()));
                if (consumerService.save(consumer)) {
                    return new CommonResult(200, true, MessageConst.ADD_USER_SUCCESS);
                } else {
                    return new CommonResult(200, false, MessageConst.ADD_USER_FAIL);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping("/{currentPage}/{pageSize}")
    @ApiOperation("用户检索")
    public CommonResult findByPageAndParam(@PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize, Consumer consumer) {
        try {
            Page<Consumer> page = consumerService.page(new Page<>(currentPage, pageSize), getWrapper(consumer));
            if (currentPage > page.getPages()) { //判断当前也是否大于总页数
                return new CommonResult(200, true, consumerService.page(new Page<>(page.getPages(), pageSize), getWrapper(consumer)));
            }
            return new CommonResult(200, true, consumerService.page(new Page<>(currentPage, pageSize), getWrapper(consumer)));
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @PostMapping("/update/{id}")
    @ApiOperation("更新用户图片")
    public CommonResult updateImg(@RequestParam("file") MultipartFile multipartFile, @PathVariable("id") Integer id) {
        if (multipartFile.isEmpty()) {
            return new CommonResult(200, false, MessageConst.UPDATE_USER_IMG_FAIL);
        }
        String fileName = System.currentTimeMillis() + multipartFile.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "avatorImages";
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        //上传后的文件地址
        File realPath = new File(filePath + System.getProperty("file.separator") + fileName);
        try {
            multipartFile.transferTo(realPath);
            Consumer consumer = consumerService.getById(id);
            File picFile = new File(System.getProperty("user.dir") + consumer.getAvator());
            if (picFile.exists()) {
                picFile.delete();
            }
            consumer.setAvator("/avatorImages/" + fileName); //更新数据库文件的相对地址
            if (consumerService.updateById(consumer)) {
                return new CommonResult(200, true, MessageConst.UPDATE_USER_IMG_SUCCESS, consumer.getAvator());
            } else {
                return new CommonResult(200, false, MessageConst.UPDATE_USER_IMG_FAIL);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @PutMapping("/update")
    @ApiOperation("更新用户")
    public CommonResult update(Consumer consumer) {
        try {
            LambdaQueryWrapper<Consumer> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(!StringUtils.isEmpty(consumer.getUsername()), Consumer::getUsername, consumer.getUsername());
            Consumer realConsumer = consumerService.getOne(wrapper);
            if (realConsumer != null) {
                if (consumer.getId() == realConsumer.getId()) {
                    //id相同说明正是当前用户,则其用户名不需改动
                    consumer.setPassword(DigestUtils.md5DigestAsHex(consumer.getPassword().getBytes()));
                    if (consumerService.updateById(consumer)) {
                        return new CommonResult(200, true, MessageConst.UPDATE_USER_SUCCESS);
                    } else {
                        return new CommonResult(200, false, MessageConst.UPDATE_USER_FAIL);
                    }
                } else {
                    return new CommonResult(200, false, MessageConst.ADMIN_NAME_FAIL);
                }
            } else {
                consumer.setPassword(DigestUtils.md5DigestAsHex(consumer.getPassword().getBytes()));
                if (consumerService.updateById(consumer)) {
                    return new CommonResult(200, true, MessageConst.UPDATE_USER_SUCCESS);
                }
                return new CommonResult(200, false, MessageConst.UPDATE_USER_FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @DeleteMapping("/delete/{idx}")
    @ApiOperation("删除用户")
    public CommonResult delete(@PathVariable("idx") String ids) {
        try {
            for (String id : Arrays.asList(ids)) {
                Consumer consumer = consumerService.getById(Integer.parseInt(id));
                Map<String, Object> map = new HashMap<>();
                map.put("consumer_id", consumer.getId());
                List<Rank> ranks = rankService.listByMap(map);
                if (ranks != null && ranks.size() > 0) {
                    rankService.removeByMap(map);
                }
                Map<String, Object> commonMap = new HashMap<>();
                commonMap.put("user_id", consumer.getId());
                List<Comment> comments = commentService.listByMap(commonMap);
                if (comments != null && comments.size() > 0) {
                    commentService.removeByMap(commonMap);
                }
                List<Collect> collects = collectService.listByMap(commonMap);
                if (collects != null && collects.size() > 0) {
                    collectService.removeByMap(commonMap);
                }
                File picFile = new File(System.getProperty("user.dir") + consumer.getAvator());
                if (consumerService.removeById(consumer.getId())) {
                    if (picFile.exists()) {
                        picFile.delete();
                    }
                }
            }
            return new CommonResult(200, true, MessageConst.DELETE_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.DELETE_USER_FAIL);
        }
    }

    @GetMapping
    @ApiOperation("获取所有用户信息")
    public CommonResult count() {
        try {
            return new CommonResult(200, true, consumerService.list());
        } catch (Exception e) {
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping("/{id}")
    @ApiOperation("获取指定id的用户详情")
    public CommonResult count(@PathVariable("id") Integer id) {
        try {
            Consumer consumer = consumerService.getById(id);
            if (consumer != null) {
                return new CommonResult(200, true, consumer);
            }
            return new CommonResult(200, false, MessageConst.GET_USER_FAIL);
        } catch (Exception e) {
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public CommonResult login(Consumer consumer) {
        try {
            LambdaQueryWrapper<Consumer> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(!StringUtils.isEmpty(consumer.getUsername()), Consumer::getUsername, consumer.getUsername());
            wrapper.eq(!StringUtils.isEmpty(consumer.getPassword()), Consumer::getPassword, DigestUtils.md5DigestAsHex(consumer.getPassword().getBytes()));
            Consumer realConsumer = consumerService.getOne(wrapper);
            if (realConsumer != null) {
                return new CommonResult(200, true, MessageConst.ADMIN_LOGIN_SUCCESS, realConsumer);
            }
            return new CommonResult(200, false, MessageConst.ADMIN_LOGIN_FAIL);
        } catch (Exception e) {
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    //封装查询条件
    private QueryWrapper<Consumer> getWrapper(Consumer consumer) {
        QueryWrapper<Consumer> wrapper = new QueryWrapper<>();
        wrapper.like(!StringUtils.isEmpty(consumer.getUsername()), "username", consumer.getUsername());
        wrapper.like(!StringUtils.isEmpty(consumer.getSex()), "sex", consumer.getSex());
        wrapper.like(!StringUtils.isEmpty(consumer.getPhoneNum()), "phone_num", consumer.getPhoneNum());
        wrapper.like(!StringUtils.isEmpty(consumer.getEmail()), "email", consumer.getEmail());
        wrapper.like(!StringUtils.isEmpty(consumer.getLocation()), "location", consumer.getLocation());
        return wrapper;
    }
}

